<script setup>
import { ref, reactive, onMounted, toRaw, computed } from 'vue'
import { ElMessage } from 'element-plus'

//引入API
// import {} from '../../api/emp.js'

const loadDataCount = ref(0);//数据加载计数标识
//表单是否加载中
const formLoading = computed(()=>loadDataCount.value < 2);

const deptArr = ref([]);
function doLoadDeptDatas() {//加载部门选择框数据
    //TODO: 使用API获取数据
    setTimeout(()=>{
        let data = [
            {id:1, name:'开发部'},
            {id:2, name:'运维部'},
            {id:3, name:'销售部'},
            {id:4, name:'行政部'},
            {id:5, name:'设备部'}
        ];

        // 成功后执行以下操作
        deptArr.value = data;
        loadDataCount.value++;
    },1000);
}
const jobArr = ref([]);
function doLoadJobDatas() {//加载职位选择框数据
    //TODO: 使用API获取数据
    setTimeout(()=>{
        let data = [
            {id:1, name:'Java工程师'},
            {id:2, name:'前端工程师'},
            {id:3, name:'UI工程师'},
            {id:4, name:'人力资源'},
            {id:5, name:'部门经理'}
        ];

        // 成功后执行以下操作
        jobArr.value = data;
        loadDataCount.value++;
    },1000);
}

onMounted(()=> {//挂载后执行
    doLoadDeptDatas();//部门数据
    doLoadJobDatas();//职位数据
});

function createFormData() {//表单数据对象模板
    return {loginName:'',pwd:'',repwd:'',no:'',name:'',idCard:'',sex:1,phone:'',addr:'',marry:1,school:'',edu:'',hiredate:'',expirationTime:'',dept:{id:undefined,name:''},job:{id:undefined,name:''},status:1};
}
//表单数据
const formData = ref(createFormData());
const formRef = ref(null);//表单组件
const formRules = reactive({//校验规则
    loginName: [{required:true, validator: (rule, value, callback)=>{
        if(!value) {
            callback(new Error('请填写登录名'));
            return;
        }
        if(value.length > 30) {
            callback(new Error('登录名长度范围是1~30'));
            return;
        }
        //TODO: 发送请求,校验登录名是否重复
        setTimeout(()=>{//模拟
            if(Math.random() > 0.7) {
                callback();//成功
            } else {
                callback(new Error('该登录名已存在'));//失败
            }
        }, 1000);
    }, trigger:'blur'}],
    pwd: [{required:true, min:1, max:20, message:'长度是1~20', trigger:'blur'}],
    repwd: [{required:true, validator: (rule, value, callback)=>{
        if(!value) {
            callback(new Error('请填写确认密码'));
            return;
        }
        if(value !== formData.value.pwd) {
            callback(new Error('确认密码与密码不一致'));
            return;
        }
        callback();
    }, trigger:'blur'}],
    no: [{required:true, message:'请填写工号', trigger:'blur'}],
    name: [
        {required:true, message:'请填写姓名', trigger:'blur'},
        {min:1, max:20, message:'长度是1~20', trigger:'blur'},
    ],
    idCard: [
        {required:true, message:'请填写身份证号', trigger:'blur'},
        {min:1, max:18, message:'长度是1~18', trigger:'blur'},
    ],
    sex: [{required:true, validator: (rule, value, callback)=>{
        if(value != 1 && value != 2) {
            callback(new Error('请选择性别'));
            return;
        }
        callback();
    }, trigger:'change'}],
    phone: [{required:true, message:'请填写手机号', trigger:'blur'}],
    addr: [{required:false, max:150, message:'长度要小于150', trigger:'blur'}],
    marry: [{required:true, validator: (rule, value, callback)=>{
        if(value != 1 && value != 2) {
            callback(new Error('请选择婚姻状况'));
            return;
        }
        callback();
    }, trigger:'change'}],
    school: [{required:false, max:50, message:'长度要小于50', trigger:'blur'}],
    edu: [{required:false, max:10, message:'长度要小于10', trigger:'blur'}],
    hiredate: [{type:'string', required:true, message:'请填写生日', trigger:'change'}],
    expirationTime: [{type:'string', required:true, message:'请填写合同到期时间', trigger:'change'}],
    "dept.id": [{required:true, type:'number', message:'请选择部门', trigger:'change'}],
    "job.id": [{required:true, type:'number', message:'请选择职位', trigger:'change'}],
    status: [{required:true, message:'请选择状态', trigger:'change'}],
});
function doFormSubmit() {//表单校验与提交
    formRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('校验通过');
            //TODO: 提交添加的数据
            let params = toRaw(formData.value);
            params.deptId = formData.value.dept.id;
            params.jobId = formData.value.job.id;
            console.log('submit:', params);

            //成功后执行以下操作
            ElMessage.success('员工添加成功');
        } else { 
            console.log('校验不通过:', fields); 
            ElMessage.warning('信息有误，请查看对应的提示信息');
        }
    });;
}
function doFormReset() {//表单重置
    formRef.value.resetFields();
}

</script>
<template>
    <div class="emp-add-page-dl" >
        <div class="title-dl" >员工添加</div>
        <el-form :model="formData" label-width="130px" :rules="formRules" 
        status-icon ref="formRef" v-loading="formLoading">
            <el-form-item label="用户名：" prop="loginName">
                <el-input v-model="formData.loginName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码：" prop="pwd">
                <el-input type="password" v-model="formData.pwd" autocomplete="off" show-password />
            </el-form-item>
            <el-form-item label="确认密码：" prop="repwd">
                <el-input type="password" v-model="formData.repwd" autocomplete="off" show-password />
            </el-form-item>

            <el-form-item label="工号：" prop="no">
                <el-input v-model="formData.no" autocomplete="off" />
            </el-form-item>
            <el-form-item label="姓名：" prop="name">
                <el-input v-model="formData.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="身份证号：" prop="idCard">
                <el-input v-model="formData.idCard" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别：" prop="sex">
                <el-radio-group v-model="formData.sex">
                    <el-radio label="男" :value="1"/><el-radio label="女" :value="2"/>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号：" prop="phone">
                <el-input v-model="formData.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="居住地：" prop="addr">
                <el-input type="textarea" v-model="formData.addr" autocomplete="off" autosize />
            </el-form-item>
            <el-form-item label="婚姻状况：" prop="marry">
                <el-radio-group v-model="formData.marry">
                    <el-radio label="未婚" :value="1"/><el-radio label="已婚" :value="2"/>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="毕业学校：" prop="school">
                <el-input v-model="formData.school" autocomplete="off" />
            </el-form-item>
            <el-form-item label="学历：" prop="edu">
                <el-select v-model="formData.edu" placeholder="请选择" >
                    <el-option label="大专以下" value="大专以下"/>
                    <el-option label="大专" value="大专"/>
                    <el-option label="本科" value="本科"/>
                    <el-option label="硕士" value="硕士"/>
                    <el-option label="博士" value="博士"/>
                </el-select>
            </el-form-item>
            <el-form-item label="入职日期：" prop="hiredate">
                <el-date-picker v-model="formData.hiredate" value-format="YYYY-MM-DD" 
                placeholder="请选择" />
            </el-form-item>
            <el-form-item label="合同到期时间：" prop="expirationTime">
                <el-date-picker v-model="formData.expirationTime" value-format="YYYY-MM-DD" 
                placeholder="请选择" />
            </el-form-item>
            <el-form-item label="部门：" prop="dept.id">
                <el-select v-model="formData.dept.id" placeholder="请选择" >
                    <el-option v-for="d in deptArr" :key="d.id" :label="d.name" :value="d.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="职位：" prop="job.id">
                <el-select v-model="formData.job.id" placeholder="请选择" >
                    <el-option v-for="j in jobArr" :key="j.id" :label="j.name" :value="j.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="状态：" prop="status">
                <el-select v-model="formData.status" placeholder="请选择" >
                    <el-option label="试用" :value="1"/>
                    <el-option label="正式" :value="2"/>
                    <el-option label="离职" :value="3"/>
                    <el-option label="实习" :value="4"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="doFormSubmit">确定</el-button>
                <el-button @click="doFormReset" >重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<style scoped>
.emp-add-page-dl {
    width: 600px;
}
.title-dl {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
}
</style>